<template>
  <div>
    <!-- 信用资产管理 -->
    <!-- 已开户显示这里 -->
    <div class="container" v-if="user_state == 1">
      <div class="title"><i class="el-icon-bank-card"></i> 我的碳信用资产</div>
      <div>
        <el-card class="box-card">
          持有总量：<span class="value"
            >{{ enterpriseData.holding_quantity }}(tCO2e) |</span
          >
          可用数量：<span class="value"
            >{{ enterpriseData.available_quantity }}(tCO2e) |</span
          >
          锁定数量：<span class="value"
            >{{ enterpriseData.locked_quantity }}(tCO2e) |</span
          >
          可用金额：<span class="value"
            >{{ enterpriseData.balance }}(￥) |
          </span>
          <el-button type="success" @click="wtbDialog" plain>我想买</el-button>
          <el-button type="primary" @click="wtsDialog">我想卖</el-button>
        </el-card>
      </div>
      <div>
        <!-- 查询搜索 -->
        <div class="search_panel">
          <el-form :inline="true">
            <el-form-item label="按项目搜索">
              <el-input
                class="input_class"
                v-model="query.trade_name"
                placeholder="请输入项目名称"
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="searchDataByName">查询</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div>
        <!-- 显示交易表格 -->
        <div>
          <el-table
            :data="tableData"
            border
            style="width: 100%"
            :row-class-name="tableRowClassName"
          >
            <el-table-column prop="trade_id" label="序号" width="80">
            </el-table-column>
            <el-table-column prop="trade_name" label="项目名称" width="240">
            </el-table-column>
            <el-table-column
              prop="trade_quantity"
              label="出售量(tCO2e)"
              width="140"
            >
            </el-table-column>
            <el-table-column
              prop="trade_offer"
              label="报价(元/tCO2e)"
              width="140"
            >
            </el-table-column>
            <el-table-column prop="publish_time" label="发布时间" width="250">
            </el-table-column>
            <el-table-column prop="trade_state" label="交易状态" width="100">
              <template slot-scope="scope">
                <el-tag type="danger" v-if="scope.row.trade_state == 2">
                  {{ setOrderState(scope.row.trade_state) }}</el-tag
                >
                <el-tag type="success" v-else-if="scope.row.trade_state == 1">
                  {{ setOrderState(scope.row.trade_state) }}</el-tag
                >
                <el-tag v-else>
                  {{ setOrderState(scope.row.trade_state) }}</el-tag
                >
              </template>
            </el-table-column>
            <el-table-column prop="trade_state" label="交易类型" width="100">
              <template slot-scope="scope">
                <el-tag type="success" v-if="scope.row.trade_type == 0">
                  {{ setTradeType(scope.row.trade_type) }}</el-tag
                >
                <el-tag type="danger" v-else>
                  {{ setTradeType(scope.row.trade_type) }}</el-tag
                >
              </template>
            </el-table-column>
            <el-table-column prop="buyer_id" label="交易方式" width="120">
              <template slot-scope="scope">
                <span v-if="scope.row.buyer_id == 0">
                  <el-link :underline="false" type="success">场内交易</el-link>
                </span>
                <span v-else>
                  <el-link :underline="false" type="primary">场外交易</el-link>
                </span>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-link
                  :underline="false"
                  type="primary"
                  @click="handleShow(scope.$index, scope.row)"
                  >查看</el-link
                >
                <el-link
                  :underline="false"
                  type="success"
                  @click="submitPublish(scope.$index, scope.row)"
                  >发布</el-link
                >
                <el-link
                  :underline="false"
                  type="primary"
                  @click="handleEdit(scope.$index, scope.row)"
                  >编辑</el-link
                >
                <el-link
                  :underline="false"
                  type="danger"
                  @click="submitCancel(scope.$index, scope.row)"
                  >撤销</el-link
                >
              </template>
            </el-table-column>
          </el-table>
          <div class="pagination">
            <el-pagination
              background
              layout="total, prev, pager, next"
              :current-page="query.currentPage"
              :page-size="query.pageSize"
              :page-count="pageTotal"
              @current-change="handlePageChange"
            ></el-pagination>
          </div>
        </div>
      </div>
    </div>
    <!-- 购买弹出框 -->
    <el-dialog
      title="发布交易"
      :visible.sync="dialogBuyFormVisible"
      :append-to-body="true"
    >
      <el-form :model="formData" ref="formData" :rules="form_rules">
        <el-form-item label="交易类型" label-width="80px">
          <template>
            <el-tag type="success" v-if="formData.trade_type == 0">{{
              setTradeType(formData.trade_type)
            }}</el-tag>
            <el-tag v-else>{{ setTradeType(formData.trade_type) }}</el-tag>
          </template>
        </el-form-item>
        <el-form-item label="项目名称" label-width="80px" prop="trade_name">
          <el-input v-model="formData.trade_name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="交易量" label-width="80px" prop="trade_quantity">
          <el-input
            v-model="formData.trade_quantity"
            @input="validateQuantityInput"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="交易单价" label-width="80px" prop="trade_offer">
          <el-input
            v-model="formData.trade_offer"
            @input="validataOfferInput"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="交易总额" label-width="80px">
          <template>
            <span
              :class="
                this.formData.trade_total <= this.enterpriseData.balance
                  ? 'success'
                  : 'danger'
              "
              >{{ formData.trade_total }}</span
            >
            <span>￥ (可用金额：{{ enterpriseData.balance }}￥)</span>
          </template>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelDialog">取 消</el-button>
        <el-button type="primary" @click="validateForm('formData')"
          >确 定</el-button
        >
      </div>
    </el-dialog>
    <!-- 售卖弹出框 -->
    <el-dialog
      title="发布交易"
      :visible.sync="dialogSellFormVisible"
      :append-to-body="true"
    >
      <el-form :model="formData" ref="formData" :rules="form_rules">
        <el-form-item label="交易类型" label-width="80px">
          <template>
            <el-tag type="success" v-if="formData.trade_type == 0">{{
              setTradeType(formData.trade_type)
            }}</el-tag>
            <el-tag v-else>{{ setTradeType(formData.trade_type) }}</el-tag>
          </template>
        </el-form-item>
        <el-form-item label="项目名称" label-width="80px" prop="trade_name">
          <el-input v-model="formData.trade_name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="交易量" label-width="80px" prop="trade_quantity">
          <el-input
            v-model="formData.trade_quantity"
            @input="validateSellQuantityInput"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="交易单价" label-width="80px" prop="trade_offer">
          <el-input
            v-model="formData.trade_offer"
            @input="validateSellOfferInput"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="交易数量" label-width="80px">
          <template>
            <span
              :class="
                this.formData.trade_quantity <=
                this.enterpriseData.available_quantity
                  ? 'success'
                  : 'danger'
              "
              >{{ formData.trade_quantity }}</span
            >
            <span> (可用数量：{{ enterpriseData.available_quantity }})</span>
          </template>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelDialog()">取 消</el-button>
        <el-button type="primary" @click="validateForm('formData')"
          >确 定</el-button
        >
      </div>
    </el-dialog>
    <!-- 未开户提示去开户 -->
    <div v-if="user_state != 1">
      当前账户为开户，<router-link to="/entermanager">去申请开户</router-link>
    </div>
  </div>
</template>

<script>
import {
  getEnterprisePropertyDataAndTradeData,
  validateApplyAccount,
  publishTradeOrder,
  getTradeOrderDataByPublishId,applyTradeOrder,cancelTradeOrder
} from "@/api";

//引入精确计算 big.js
const Big = require("big.js");

export default {
  name: "PropertyView",
  data() {
    return {
      query: {
        user_id: JSON.parse(localStorage.getItem("User")).user_id,
        publish_id: JSON.parse(localStorage.getItem("User")).user_id,
        trade_name:"",
        currentPage: 1,
        pageSize: 8,
      },
      user_state: 0,
      enterpriseData: {},
      tableData: [
        {
          trade_id: 1,
          trade_name: "测试销售",
          trade_quantity: 200,
          trade_offer: 89.7,
          publish_time: "2024年8月24日",
          trade_state: 0,
          trade_type: 1,
          buyer_id: 0,
        },
        {
          trade_id: 2,
          trade_name: "测试销售",
          trade_quantity: 200,
          trade_offer: 89.7,
          publish_time: "2024年8月24日",
          trade_state: 1,
          trade_type: 0,
          buyer_id: 3,
        },
        {
          trade_id: 3,
          trade_name: "测试销售",
          trade_quantity: 200,
          trade_offer: 89.7,
          publish_time: "2024年8月24日",
          trade_state: 2,
          trade_type: 0,
          buyer_id: 5,
        },
      ],
      pageTotal: 0,
      dialogBuyFormVisible: false,
      dialogSellFormVisible: false,
      //发布订单提交表单对象
      formData: {
        trade_id:1,
        publish_id: JSON.parse(localStorage.getItem("User")).user_id, //交易订单发布人
        trade_name: "", //发布项目名称
        trade_quantity: 0, //交易数量
        trade_offer: 50.01, //单价
        trade_type: 0, //交易类型 0是求购，1是卖
        balance: 0.0, //余额
        trade_total: 0.01, //交易总金额
        trade_class: "success", //默认交易金额样式
        availableBalance: 0.0, //账户可用余额
        enable_post: true, //默认允许提交
      },
      //确认发布和撤销时提交表单对象
      submitData:{

      },
      form_rules: {
        trade_name: [
          { required: true, message: "请输入项目名称", trigger: "blur" },
        ],
        trade_quantity: [
          { required: true, message: "请输入交易数量", trigger: "blur" },
        ],
        trade_offer: [
          { required: true, message: "请输入单价", trigger: "blur" },
        ],
      },
    };
  },
  mounted() {
    this.initData();
  },
  methods: {
    initData() {
      this.validateApplyAccount();
      this.formData.availableBalance = this.enterpriseData.balance;
    },
    //我要买
    wtbDialog() {
      this.formData.trade_type = 0; //设置交易类型：买方
      this.dialogBuyFormVisible = true;
    },
    //我要卖
    wtsDialog() {
      this.formData.trade_type = 1; //设置交易类型：卖方
      this.dialogSellFormVisible = true;
    },
    //我要买请求处理函数
    //验证表单输入
    validateForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          //验证输入成功
          if (!this.formData.enable_post) {
            //余额不足，不能提交
            this.$message.error("余额或可用量不足，请重新输入");
          } else {
            //可发布交易
            this.publishTradeOrderHandler();
          }
        } else {
          //验证输入失败
          return;
        }
      });
    },
    //提交发布交易处理程序
    async publishTradeOrderHandler() {
      let res = await publishTradeOrder(this.formData);
      if (res.code == 200) {
        this.$message({
          message: res.msg,
          type: "success",
        });
        this.dialogBuyFormVisible = false;
        this.dialogSellFormVisible = false;
        //初始化数据加载
        this.initData();
      } else {
        this.$message.error(res.msg);
      }
    },
    //验证输入单价只能小数点后1-2位
    validataOfferInput(value) {
      // 使用正则表达式匹配小数点后只能有最多两位小数
      const regex = /^(\d+)?(\.\d{1,2})?$/;
      if (!regex.test(value)) {
        this.formData.trade_offer = this.formData.trade_offer.substring(
          0,
          value.length - 1
        );
      }
      //实时计算验证
      this.CalculateTotalPrice();
      //实时余额是否满足可用要求
      this.validateAvailableBalance();
    },
    //验证数量输入不能小于0
    validateQuantityInput(value) {
      // 使用正则表达式来确保输入的是数字，并且不低于0
      const regex = /^(?:[1-9]\d*|0)$/;
      if (!regex.test(value)) {
        this.formData.trade_quantity = this.formData.trade_quantity.substring(
          0,
          this.formData.trade_quantity.length - 1
        );
      }
      //实时计算验证
      this.CalculateTotalPrice();
      //实时余额是否满足可用要求
      this.validateAvailableBalance();
    },
    //验证可用余额
    validateAvailableBalance() {
      //可用余额
      let availableBalance = this.enterpriseData.balance;
      let balance = this.CalculateTotalPrice();
      //交易数量乘以交易单价小于等于余额
      if (balance <= availableBalance) {
        //交易可进行
        this.formData.enable_post = true;
      } else {
        //不可交易提示错误
        this.formData.enable_post = false;
        // this.$message.error("余额不足，请重新输入");
      }
    },
    //输入数量或者单价时，实时计算交易总金额
    CalculateTotalPrice() {
      // let offer = this.formData.trade_offer;
      // let counts = this.formData.trade_quantity;
      // this.formData.trade_total = offer * counts;
      //替换下面写法
      let offer = new Big(this.formData.trade_offer);
      let counts = new Big(this.formData.trade_quantity);
      this.formData.trade_total = offer.times(counts);
      return offer.times(counts);
    },
    //验证销售框输入数量验证
    validateSellQuantityInput(value) {
      // 使用正则表达式来确保输入的是数字，并且不低于0
      const regex = /^(?:[1-9]\d*|0)$/;
      if (!regex.test(value)) {
        this.formData.trade_quantity = this.formData.trade_quantity.substring(
          0,
          this.formData.trade_quantity.length - 1
        );
      }
      //实时计算交易数量是否可用
      this.validateAvailableQuantity();
    },
    //验证销售框输入单价
    validateSellOfferInput(value) {
      // 使用正则表达式匹配小数点后只能有最多两位小数
      const regex = /^(\d+)?(\.\d{1,2})?$/;
      if (!regex.test(value)) {
        this.formData.trade_offer = this.formData.trade_offer.substring(
          0,
          value.length - 1
        );
      }
      //实时计算交易数量是否可用
      this.validateAvailableQuantity();
    },
    //验证销售数量不能大于可用数量
    validateAvailableQuantity() {
      let quantity = this.formData.trade_quantity;
      let available_quantity = this.enterpriseData.available_quantity;
      if (quantity <= available_quantity) {
        //可以交易
        this.formData.enable_post = true;
      } else {
        //不可交易
        this.formData.enable_post = false;
      }
    },
    //设置订单状态
    setOrderState(num) {
      switch (num) {
        case 0:
          return "未发布";
        case 1:
          return "已经发布";
        case 2:
          return "交易完成";
      }
    },
    //设置交易类型
    setTradeType(num) {
      switch (num) {
        case 0:
          return "买方";
        case 1:
          return "卖方";
      }
    },
    //验证开户状态
    async validateApplyAccount() {
      let res = await validateApplyAccount(this.query);
      // console.log(res);
      if (res.code == 201) {
        this.user_state = res.data;
      } else if (res.code == 200) {
        this.user_state = 1; //已开通状态
        //加载数
        this.enterpriseData = res.data;
        //已经开通则加载订单列表分页数据
        this.getTradeOrderDataByPublishId();
      }
    },
    //加载订单数据根据发布人id
    async getTradeOrderDataByPublishId() {
      let res = await getTradeOrderDataByPublishId(this.query);
      console.log(res);
      if (res.code == 200) {
        this.tableData = res.data.data;
        this.pageTotal = res.data.pageTotal;
      }
    },
    //加载资产数据和交易数据
    async getEnterprisePropertyDataAndTradeData() {
      let res = await getEnterprisePropertyDataAndTradeData(this.query);
      console.log(res);
      if (res.code == 200) {
        // this.tableData = res.data.propertyData;
      }
    },
    //搜索方法
    searchDataByName(){
      this.getTradeOrderDataByPublishId();
      this.query.trade_name = "";
    },
    tableRowClassName({ row, rowIndex }) {
      if (rowIndex === 1) {
        return "warning-row";
      } else if (rowIndex === 3) {
        return "success-row";
      }
      return "";
    },
    handleShow(index, row) {
      console.log(index, row);
    },
    handleEdit(index, row) {
      console.log(index, row);
    },
    handleDelete(index, row) {
      console.log(index, row);
    },
    // 分页导航
    handlePageChange(val) {
      // console.log(val);
      // this.$set(this.query, 'currentPage', val);
      this.query.currentPage = val;
      this.initData();
    },
    //点击取消按钮的时候，提交表单的值初始化
    cancelDialog() {
      this.dialogBuyFormVisible = false;
      this.dialogSellFormVisible = false;
      // trade_name: "", //发布项目名称
      //   trade_quantity: 0, //交易数量
      //   trade_offer: 50.01, //单价
      //   trade_type: 0, //交易类型 0是求购，1是卖
      //   balance: 0.0, //余额
      //   trade_total: 0.01, //交易总金额
      //   trade_class: "success", //默认交易金额样式
      //   availableBalance: 0.0, //账户可用余额
      //   enable_post: true, //默认允许提交
      this.formData.trade_name = "";
      this.formData.trade_quantity = 0;
      this.formData.trade_offer = 50.01;
      this.formData.trade_type = 0;
      this.formData.balance = 0.0;
      this.formData.trade_total = 0.0;
      this.formData.availableBalance = 0.0;
      this.formData.enable_post = true;
    },
    //发布确认
    submitPublish(index, row) {
      // 二次确认删除
      this.$confirm("确定要发布该订单吗？", "提示", {
        type: "success",
      })
        .then(() => {
          this.submitData = row;
          this.applyTradeOrder();  
          this.initData();        
        })
        .catch(() => {});
    },
    //确认发布订单
    async applyTradeOrder(){
      let res = await applyTradeOrder(this.submitData);
      if(res.code == 200){
        this.$message({
          message: res.msg,
          type: "success",
        });
      }else{
        this.$message.error(res.msg);
      }
    },
    //撤销订单发布
    submitCancel(index, row) {
      // 二次确认删除
      this.$confirm("确定要撤销该订单吗？", "提示", {
        type: "warning",
      })
        .then(() => {
          this.submitData = row;
          this.cancelTradeOrder();
          this.initData();
        })
        .catch(() => {});
    },
    //确认撤销订单
    async cancelTradeOrder(){
      let res =await cancelTradeOrder(this.submitData);
      if(res.code == 200){
        this.$message({
          message: res.msg,
          type: "success",
        });
      }else{
        this.$message.error(res.msg);
      }
    },
  },
};
</script>

<style scoped>
.title {
  font-size: 18px;
  color: #23aa74;
}

.box-card {
  margin-top: 10px;
  background: #e7f7ef;
  font-size: 18px;
}

.box-card .value {
  color: #23aa74;
}

.search_panel {
  margin-top: 10px;
}

.input_class {
  width: 350px;
}

.el-table .warning-row {
  background: oldlace;
}

.el-table .success-row {
  background: #f0f9eb;
}

.el-link {
  margin-right: 10px;
}

.success {
  color: #0bd46f;
}

.danger {
  color: #ff0000;
}
</style>